import { App, Empty, Input, Modal, Popover, Segmented, Skeleton } from 'antd'
import { SegmentedValue } from 'antd/es/segmented'
import cs from 'classnames'
import Image from 'next/image'
import { useContext, useEffect, useRef, useState } from 'react'

import { Violation } from '@/api/interface'
import { ReplyRes } from '@/api/interface/entity'
import { UploadFile } from '@/api/modules/entity'
import { Reply, ReplyList } from '@/api/modules/entity'
import alert from '@/assets/images/alert-circle.png'
import close from '@/assets/images/close.png'
import file from '@/assets/images/file.png'
import repliedAvatar from '@/assets/images/replied-logo.png'
import { GlobalContext } from '@/context'
import eventBus from '@/utils/EventBus'
import useLocale from '@/utils/useLocale'

import locale from './locale'
import styles from './styles/index.module.less'

const { TextArea } = Input

const fileTypes = [
  'image/pjpeg',
  'image/jpeg',
  'image/png',
  'application/msword',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  'application/vnd.ms-excel',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  'application/pdf',
]

function EntityReply({
  violation,
  isModalOpen,
  setIsModalOpen,
  refresh,
}: {
  violation: Partial<Violation>
  isModalOpen: boolean
  setIsModalOpen: (_: boolean) => void
  refresh: () => void
}) {
  const t = useLocale(locale)

  const { lang } = useContext(GlobalContext)

  const { message } = App.useApp()

  const [type, setType] = useState<SegmentedValue>('unReplied')
  const changeType = (value: SegmentedValue) => {
    setType(value)
  }

  const [fileList, setFileList] = useState<string[]>([])

  const FileUploadComponent = () => {
    const fileInputRef = useRef<HTMLInputElement | null>(null)
    const handleFileSelect = () => {
      if (fileInputRef.current) {
        fileInputRef.current.value = ''
        fileInputRef.current.click()
      }
    }

    const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
      const files = e.target.files
      if (files?.length! > 5) return message.warning(t['reply.attachments.upload.length.warning'])
      if (files) {
        const uploadPromises = Array.from(files).map(async (file) => {
          const imgType = fileTypes.includes(file.type)
          const imgSize = file.size / 1024 / 1024 < 200
          if (!imgType) {
            message.warning(t['reply.attachments.upload.type.warning'])
            return null
          }
          if (!imgSize) {
            message.warning(t['reply.attachments.upload.size.warning'])
            return null
          }

          const excelFormData = new FormData()
          excelFormData.append('file', file)
          const { data } = await UploadFile(excelFormData)
          return data
        })

        const uploadedFiles = await Promise.all(uploadPromises)

        // Filter out null values (warnings) and update the state with uploaded files
        const filteredFiles = uploadedFiles.filter((file) => file !== null) as string[]

        setFileList([...fileList, ...filteredFiles])
      }
    }

    const delFile = (file: string) => {
      setFileList(fileList?.filter((item) => item !== file))
    }

    return (
      <>
        {fileList.length ? (
          <div className={styles['un-replied-attachments-file']}>
            {fileList.map((item) => {
              return (
                <div className={styles['un-replied-attachments-file-item']} key={item}>
                  <Image src={file} className={styles['file-icon']} alt="file" />
                  <span className={styles['file-text']}>{item}</span>
                  <Image
                    onClick={() => delFile(item)}
                    src={close}
                    className={styles['file-close']}
                    alt="close"
                  />
                </div>
              )
            })}
          </div>
        ) : (
          <></>
        )}

        <div className={styles['un-replied-attachments-add']}>
          <span onClick={handleFileSelect}>{t['reply.attachments.add']}</span>
          <input
            type="file"
            multiple
            style={{ display: 'none' }}
            ref={fileInputRef}
            onChange={handleFileUpload}
            accept=".jpeg,.png,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.pdf"
          />
        </div>
      </>
    )
  }

  useEffect(() => {
    isModalOpen && getRepliedList()
    setFileList([])
    setType('unReplied')
  }, [isModalOpen])

  const [loading, setLoading] = useState(true)
  const [unReplied, setUnReplied] = useState<ReplyRes[]>([])
  const [replied, setReplied] = useState<ReplyRes[][]>([])
  const getRepliedList = async () => {
    try {
      setLoading(true)
      // unReplied
      const { data } = await ReplyList({ refNumber: violation.refNumber! })
      const unReplied = data.filter((item) => item.status === 0 && item.source === 'INT')
      unReplied.length && setRepliedActive(unReplied[0])
      setUnReplied(unReplied)

      // replied
      const filteredData = []
      if (data.length === 1) {
        filteredData.push(data)
      } else {
        for (let i = 0; i < data.length; i++) {
          const obj = data[i]
          const matchingObj = data.find((item) => item.id === obj.replyTo)
          if (matchingObj) {
            const index = filteredData.findIndex((arr) =>
              arr.some((el) => el.id === matchingObj.id)
            )
            if (index !== -1) filteredData[index].push(obj)
            else filteredData.push([matchingObj, obj])
          }
        }
      }
      setReplied(filteredData)
    } finally {
      setLoading(false)
    }
  }

  const [repliedActive, setRepliedActive] = useState<Partial<ReplyRes>>({})
  const clickReplied = (item: ReplyRes) => {
    if (item.id === repliedActive.id) return
    setFileList([])
    setRepliedActive(item)
  }

  const handleCancel = () => {
    setIsModalOpen(false)
  }

  const [content, setContent] = useState('')

  const handleSubmit = async () => {
    if (!content || content.length < 5) return message.warning(t['reply.content.error'])
    const params = {
      attachment: fileList,
      content: content,
      refNumber: violation.refNumber!,
      replyTo: repliedActive.id!,
    }
    await Reply(params)
    message.success(t['reply.content.success'])
    setIsModalOpen(false)
    refresh()
    eventBus.emit('CLICKNOTICE')
  }

  return (
    <Modal
      centered
      width={905}
      title={violation.refNumber}
      footer={false}
      open={isModalOpen}
      onCancel={handleCancel}
      className={styles['reply-modal']}
      classNames={{
        header: styles['reply-header'],
        body: styles['reply-body'],
      }}
      wrapClassName={styles['reply-wrapper']}
    >
      <Skeleton
        loading={loading}
        title={false}
        active
        paragraph={{ rows: 17 }}
        style={{ padding: '20px' }}
      >
        <Segmented
          value={type}
          className={styles['reply-segmented']}
          onChange={changeType}
          options={[
            {
              label: (
                <>
                  {t['reply.segmented.unReplied']}
                  {violation.unRepliedCount != 0 && (
                    <span className={styles['segmented-title-num']}>
                      {violation.unRepliedCount}
                    </span>
                  )}
                </>
              ),
              value: 'unReplied',
            },
            {
              label: t['reply.segmented.replied'],
              value: 'replied',
            },
          ]}
        />
        {type === 'unReplied' && (
          <div className={styles['un-replied']}>
            {unReplied.length ? (
              <>
                <div className={styles['un-replied-left']}>
                  <div className={styles['un-replied-left-list']}>
                    {unReplied.map((item) => {
                      return (
                        <div
                          className={cs(
                            styles['un-replied-item'],
                            item.id === repliedActive.id && styles['un-replied-item-active']
                          )}
                          key={item.id}
                          onClick={() => clickReplied(item)}
                        >
                          <div className={styles['un-replied-item-main']}>
                            <Image
                              src={repliedAvatar}
                              className={styles['un-replied-item-avatar']}
                              alt="replied-avatar"
                            />
                            <div className={styles['un-replied-item-content']}>
                              <div className={styles['un-replied-item-title']}>
                                <span className={styles['un-replied-item-name']}>
                                  {item.createdBy}
                                  {/* {'WAJIB'} */}
                                </span>
                                <span className={styles['un-replied-item-date']}>
                                  {item.createdAt.substring(0, 10)}
                                </span>
                              </div>
                              <span className={styles['un-replied-item-description']}>
                                {item.content ? item.content : '--'}
                              </span>
                            </div>
                          </div>
                        </div>
                      )
                    })}
                  </div>
                </div>

                <div className={styles['un-replied-right']}>
                  <div className={styles['un-replied-right-title']}>
                    <div className={styles['un-replied-title-logo']}>
                      <Image
                        src={repliedAvatar}
                        className={styles['un-replied-title-avatar']}
                        alt="replied-avatar"
                      />
                      <span className={styles['un-replied-title-name']}>
                        {repliedActive.createdBy}
                      </span>
                    </div>
                    <span className={styles['un-replied-title-date']}>
                      {repliedActive.createdAt}
                    </span>
                  </div>
                  <div className={styles['un-replied-detail']}>
                    <span className={styles['un-replied-detail-start']}>
                      <span>‘</span>
                      <span>‘</span>
                    </span>
                    <span className={styles['un-replied-detail-text']}>
                      {repliedActive.content ? repliedActive.content : '--'}
                    </span>
                    <span className={styles['un-replied-detail-end']}>
                      <span>’</span>
                      <span>’</span>
                    </span>
                  </div>
                  <div className={styles['un-replied-textarea']}>
                    <span className={styles['un-replied-textarea-label']}>{t['reply.title']}</span>
                    <TextArea
                      rows={6}
                      placeholder={t['reply.content.placeholder']}
                      showCount
                      maxLength={1000}
                      onChange={(e) => setContent(e.target.value)}
                    />
                  </div>
                  <div className={styles['un-replied-attachments']}>
                    <span className={styles['un-replied-attachments-label']}>
                      {t['reply.attachments']}
                      <Popover
                        placement={lang === 'en-US' ? 'right' : 'left'}
                        content={t['reply.attachments.upload.type']}
                      >
                        <Image
                          src={alert}
                          alt="alert"
                          className={styles['un-replied-attachments-alert-icon']}
                        ></Image>
                      </Popover>
                    </span>
                    <FileUploadComponent />
                  </div>
                  <div
                    className={styles['un-replied-right-footer']}
                    style={lang === 'en-US' ? { right: '24px' } : { left: '24px' }}
                  >
                    <div className={styles['un-replied-submit']} onClick={() => handleSubmit()}>
                      <span className={styles['un-replied-submit-text']}>{t['reply.submit']}</span>
                    </div>
                  </div>
                </div>
              </>
            ) : (
              <Empty description={false} />
            )}
          </div>
        )}

        {type === 'replied' && (
          <div className={styles['replied']}>
            {replied.length ? (
              <div className={styles['replied-list']}>
                {replied.map((item, index) => {
                  return (
                    <div className={styles['replied-item']} key={index}>
                      <div className={styles['replied-header']} />
                      <div className={styles['replied-main']}>
                        <div className={styles['replied-comment']}>
                          {item.map((subItem, subIndex) => {
                            return (
                              <div className={styles['replied-comment-item']} key={subIndex}>
                                <div className={styles['replied-comment-header']}>
                                  <span className={styles['comment-title']}>
                                    {`${subItem.createdBy} ${
                                      subItem.source === 'INT' ? 'commented :' : 'replied :'
                                    } `}
                                  </span>
                                  <span className={styles['comment-time']}>
                                    {subItem.createdAt}
                                  </span>
                                </div>
                                <span className={styles['comment-text']}>
                                  {subItem.content ? subItem.content : '--'}
                                </span>
                                {subItem.attachment?.length ? (
                                  <div className={styles['replied-file']}>
                                    {subItem.attachment?.map((item) => {
                                      return (
                                        <div className={styles['replied-file-item']} key={item}>
                                          <Image
                                            src={file}
                                            className={styles['file-icon']}
                                            alt="file"
                                          />
                                          <span className={styles['file-text']}>{item}</span>
                                        </div>
                                      )
                                    })}
                                  </div>
                                ) : (
                                  <></>
                                )}
                              </div>
                            )
                          })}
                        </div>
                      </div>
                    </div>
                  )
                })}
              </div>
            ) : (
              <Empty description={false} />
            )}
          </div>
        )}
      </Skeleton>
    </Modal>
  )
}
export default EntityReply
